package com.phkj.qdh.ui.fragment.usecar

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.RelativeLayout
import android.widget.Toast
import androidx.activity.OnBackPressedCallback
import androidx.core.content.ContextCompat
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.commit
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter4.QuickAdapterHelper
import com.chad.library.adapter4.loadState.LoadState
import com.chad.library.adapter4.loadState.trailing.TrailingLoadStateAdapter
import com.flyco.tablayout.listener.CustomTabEntity
import com.flyco.tablayout.listener.OnTabSelectListener
import com.google.android.material.tabs.TabLayout.Tab
import com.hjq.toast.ToastUtils
import com.phkj.qdh.R
import com.phkj.qdh.base.BaseVM
import com.phkj.qdh.base.BaseVM.Companion.STATE_FAIL
import com.phkj.qdh.base.BaseVM.Companion.STATE_SUCCESS
import com.phkj.qdh.bean.MyTab
import com.phkj.qdh.bean.PageInfo
import com.phkj.qdh.databinding.FragmentUseCarMainBinding
import com.phkj.qdh.ui.adapter.UseCarApprovalAdapter
import com.phkj.qdh.ui.adapter.UseCarSubmitAdapter
import com.phkj.qdh.utils.LogUtil
import com.phkj.qdh.utils.MyItemDecoration
import com.phkj.qdh.utils.PAGE_SIZE
import com.phkj.qdh.utils.gone
import com.phkj.qdh.utils.launchAndRepeatWithViewLifecycle
import com.phkj.qdh.utils.visible
import kotlinx.coroutines.flow.collectLatest
import java.util.ArrayList

private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"

/**
 * 使用车辆页面
 */
class UseCarMainFragment : Fragment() {
    private var param1: String? = null
    private var param2: String? = null
    private var _binding: FragmentUseCarMainBinding? = null
    private val binding get() = _binding!!
    private lateinit var vm: CarVM
    private var pos = 0  //0申请 1审核

    private val useCarSubmitAdapter by lazy { UseCarSubmitAdapter() }
    private val approveCarSubmitAdapter by lazy { UseCarApprovalAdapter() }

    //申请适配器
    private lateinit var useHelper: QuickAdapterHelper
    private val useCarPageInfo = PageInfo()
    private val approvalCarPageInfo = PageInfo()

    //审核适配器
    private lateinit var approveHelper: QuickAdapterHelper

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            param1 = it.getString(ARG_PARAM1)
            param2 = it.getString(ARG_PARAM2)
        }
        requireActivity().onBackPressedDispatcher.addCallback(
            this,
            object : OnBackPressedCallback(true) {
                override fun handleOnBackPressed() {
                    parentFragmentManager.popBackStack()
                }
            })
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentUseCarMainBinding.inflate(inflater, container, false)
        vm = ViewModelProvider(this, getCarVMProvider())[CarVM::class.java]
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.run {
            ivBack.setOnClickListener {
                parentFragmentManager.popBackStack("car", FragmentManager.POP_BACK_STACK_INCLUSIVE)

            }
            rvUseCar.run {
                layoutManager = LinearLayoutManager(requireContext())
                addItemDecoration(MyItemDecoration(width = 24))

            }
            ivSubmit.setOnClickListener {
                parentFragmentManager.commit {
                    addToBackStack("car_submit")
                    replace(id, UseCarSubmitFragment.newInstance("", ""))
                    setReorderingAllowed(true)
                }
            }
            srlUseCar.setOnRefreshListener {
                if (pos == 0) {
                    refreshUseCarList()
                } else {
                    refreshUseCarApprovalList()
                }
            }
        }

        useHelper = QuickAdapterHelper.Builder(useCarSubmitAdapter)
            .setTrailingLoadStateAdapter(object : TrailingLoadStateAdapter.OnTrailingListener {
                override fun onFailRetry() {
                    getUseCarList()
                }

                override fun onLoad() {
                    useCarPageInfo.nextPage()
                    getUseCarList()
                }

                override fun isAllowLoading(): Boolean {
                    return !binding.srlUseCar.isRefreshing
                }
            }).build()
        useCarSubmitAdapter.setStateViewLayout(requireContext(), R.layout.item_empty)
        binding.rvUseCar.adapter = useHelper.adapter
        useCarSubmitAdapter.setOnItemClickListener{adapter,_,pos->
            parentFragmentManager.commit {
                replace(id,UseCarDetailMyFragment.newInstance(adapter.getItem(pos)!!,""))
                addToBackStack("my_detail")
                setReorderingAllowed(true)
            }

        }

        approveHelper = QuickAdapterHelper.Builder(approveCarSubmitAdapter)
            .setTrailingLoadStateAdapter(object : TrailingLoadStateAdapter.OnTrailingListener {
                override fun onFailRetry() {
                    getUseCarApproval()
                }

                override fun onLoad() {
                    approvalCarPageInfo.nextPage()
                    getUseCarApproval()
                }

                override fun isAllowLoading(): Boolean {
                    return !binding.srlUseCar.isRefreshing
                }
            }).build()


        approveCarSubmitAdapter.setOnItemClickListener{adapter,_,pos->
            parentFragmentManager.commit {
                replace(id,UseCarApprovalFragment.newInstance(adapter.getItem(pos)!!,""))
                addToBackStack("my_approval")
                setReorderingAllowed(true)
            }

        }
        launchAndRepeatWithViewLifecycle {
            vm.hasPermission.collectLatest {
                if (it) {
                    binding.ctl.visible()
                    binding.ctl.run {
                        setTabData(arrayListOf(MyTab("用车申请"), MyTab("我的审批")))
                        getMsgView(1).backgroundColor =
                            ContextCompat.getColor(requireContext(), R.color.main_color)
                        getMsgView(1).textSize = 12f
                        //设置边距
                    }

                    binding.ctl.setOnTabSelectListener(object : OnTabSelectListener {
                        override fun onTabSelect(position: Int) {
                            binding.srlUseCar.isRefreshing = false
                            if (position == 0) {
                                pos = 0
                                binding.rvUseCar.adapter = useHelper.adapter
                                binding.ivSubmit.visible()
                            } else {
                                pos = 1
                                binding.rvUseCar.adapter = approveHelper.adapter
                                binding.ivSubmit.gone()
                            }
                        }

                        override fun onTabReselect(position: Int) {

                        }
                    })
                    getUseCarList()
                    getUseCarApproval()
                } else {
                    binding.ctl.gone()
                    getUseCarList()
                }
            }
        }

        launchAndRepeatWithViewLifecycle {
            vm.uiState.collectLatest {
                if (it == BaseVM.STATE_NORMAL) {
//                    binding.srlUseCar.isRefreshing = false
//                    ToastUtils.show("加载完成")
                }
            }
        }

        launchAndRepeatWithViewLifecycle {
            vm.useCarMyList.collectLatest {
                if (useCarPageInfo.isFirstPage) {
                    useCarSubmitAdapter.submitList(it)
                } else {
                    useCarSubmitAdapter.addAll(it)
                }
                binding.srlUseCar.isRefreshing = false
                if (it.size != PAGE_SIZE) {/*

                    Set the status to not loaded, and there is no paging data.
                    设置状态为未加载，并且没有分页数据了
                     */
                    useHelper.trailingLoadState = LoadState.NotLoading(true)
                } else {/*
                    Set the state to not loaded, and there is also paginated data
                    设置状态为未加载，并且还有分页数据
                     */
                    useHelper.trailingLoadState = LoadState.NotLoading(false)
                }
            }
        }
        launchAndRepeatWithViewLifecycle {//审核列表
            vm.useCarList.collectLatest {

                if (approvalCarPageInfo.isFirstPage) {
                    approveCarSubmitAdapter.submitList(it)
                } else {
                    approveCarSubmitAdapter.addAll(it)
                }

                val unRead = it.filter { list ->list.applyStatus == 0 }
                if (unRead.isNotEmpty()) binding.ctl.showMsg(1,unRead.size) else binding.ctl.hideMsg(1)
                binding.srlUseCar.isRefreshing = false
                if (it.size != PAGE_SIZE) {/*

                    Set the status to not loaded, and there is no paging data.
                    设置状态为未加载，并且没有分页数据了
                     */
                    approveHelper.trailingLoadState = LoadState.NotLoading(true)
                } else {/*
                    Set the state to not loaded, and there is also paginated data
                    设置状态为未加载，并且还有分页数据
                     */
                    approveHelper.trailingLoadState = LoadState.NotLoading(false)
                }
            }
        }
        hasPermission()

    }

    override fun onResume() {
        super.onResume()
        if (binding.ctl.currentTab==1){
            binding.ivSubmit.gone()
            binding.rvUseCar.adapter = approveHelper.adapter
        }else{
            binding.ivSubmit.visible()
            binding.rvUseCar.adapter = useHelper.adapter
        }
        LogUtil.E("onResume$pos")
    }

    private fun hasPermission() {
        vm.hasPermission()
    }

    private fun getUseCarList() {
        val map = HashMap<String, Any?>()
        map["page"] = useCarPageInfo.page
        map["size"] = PAGE_SIZE
        vm.getUseCarMyList(map)
    }

    private fun refreshUseCarList() {
        useCarPageInfo.reset()
        useHelper.trailingLoadState = LoadState.None
        getUseCarList()
    }

    private fun refreshUseCarApprovalList() {
        approvalCarPageInfo.reset()
        approveHelper.trailingLoadState = LoadState.None
        getUseCarApproval()
    }

    private fun getUseCarApproval() {
        val map = HashMap<String, Any?>()
        map["page"] = approvalCarPageInfo.page
        map["size"] = PAGE_SIZE
        vm.getUseCarList(map)
    }

    companion object {
        @JvmStatic
        fun newInstance(param1: String, param2: String) = UseCarMainFragment().apply {
            arguments = Bundle().apply {
                putString(ARG_PARAM1, param1)
                putString(ARG_PARAM2, param2)
            }
        }
    }
}